<?php
namespace api\modules\v1\models;

use Yii;
use yii\base\Model;

/**
 * Signup form
 */
class ForgetForm extends Model
{
    public $mobile;
    public $password;
    public $vcode;
    public $verify_code;
    public $timestamp;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['mobile', 'vcode', 'verify_code', 'password', 'timestamp'], 'filter', 'filter' => 'trim'],
            [['mobile', 'vcode', 'verify_code', 'password', 'timestamp'], 'required'],
            
            [['mobile', 'vcode', 'timestamp'], 'number'],            
            ['mobile', 'string', 'length' => [11, 11]],
            ['vcode', 'string', 'max' => 6],
            ['timestamp', 'string', 'max' => 10],
            ['verify_code', 'string', 'max' => 32],
            ['password', 'string', 'length' => [6, 24]],
        ];
    }
    
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'mobile' => Yii::t('app', '手机号'),
            'vcode' => Yii::t('app', '验证码'),
            'verify_code' => Yii::t('app', '加密验证码'),
            'timestamp' => Yii::t('app', '时间戳'),
            'password' => Yii::t('app', '会员密码'),
        ];
    }

    /**
     * @inheritdoc
     */
    public function resetPassword()
    {
        if ($this->validate()) {
            // 校验验证码
            // 4dcb61931cd9d4b17acf3d153e3624f4 18638923187 1432647819 268864
            $verify_code = md5($this->mobile . $this->vcode . $this->timestamp);
            if ($verify_code != $this->verify_code) {
                $this->addError('vcode', '验证码错误');
                return $this;
            }
            if(time()>$this->timestamp){
                $this->addError('vcode','验证码已过期');
            }
            $user = Member::findByMobile($this->mobile);
            $user->member_passwd = md5($this->password);
            $user->member_old_login_time = $user->member_login_time;
            $user->member_login_time = strval(time());
            $user->member_old_login_ip = $user->member_login_ip;
            $user->member_login_ip = $_SERVER['REMOTE_ADDR'];
            if ($user->update()) {
                $token = new LoginForm();
                return $token->createToken($user->member_id, $user->member_name, 'android');
            } else {
                return $user;
            }
        } else {
            return $this;
        }
    }
}
